<?php
/**
 *  支付接口 .
 * User: myl
 * Date: 2018/8/116
 * Time: 15:41

 */
namespace app\api\controller;

use think\Db;

class Pay extends Base
{
    /**
     * 微信支付（公众号）
     * @return mixed
     */
    public function wxPay()
    {
        if (!empty($_GET['out_trade_no'])) {
            session('out_trade_no',$_GET['out_trade_no']); //订单号
            session('total_fee',$_GET['total_fee']); //价格
            session('total_fee2',$_GET['total_fee2']); //微信支付类型（total_fee2：充值）
        } else {
            $out_trade_no = session('out_trade_no');
            $total_fee = session('total_fee');
            $total_fee2 = session('total_fee2');
        }
        //导入微信支付sdk
        $wxpay = new Wxpay();
        if (!isset($_GET['code'])) {
            $wxpay->start();
        } else {
            $code = $_GET['code'];
            $access_token = $wxpay->getUserAccessToken($code); //获取授权token
            $UserInfo = $wxpay->getUserInfo($access_token); //获取用户信息
            $openid = $UserInfo['openid'];
        }
        if ($total_fee2 == 2) {
            //余额充值
            $notify_url = 'http://vip.bndvip.com/api/Wxpay/rechargeNotify';
        } else {
            //订单支付
            $notify_url = 'http://vip.bndvip.com/api/Wxpay/callbackNotify';
        }
        $total_fee_money = $total_fee*100;
        $total_fees = intval($total_fee_money);
        $data = $wxpay->getPrePayOrder($out_trade_no,$openid,$total_fees,$notify_url);
        session('out_trade_no',null);
        session('total_fee',null);
        session('payType',null);
        //将数据分配到前台页面
        $data2 = json_encode($data);
        $this->assign('data3', $data2);
        return $this->fetch();
    }

    /**
     * 余额支付
     */
    public function balancePay()
    {
        $out_trade_no = $_GET['out_trade_no2'];

        /** 业务逻辑流程 **/
        /**1*///修改订单（订单状态、支付时间）
        $data['pay_status'] = 1;
        $data['pay_time'] = time();
        $data['pay_code'] = 'code';
        $data['pay_name'] = '余额支付';
        //修改订单（支付转态，支付时间）
        M("order")->where(["order_sn"=>$out_trade_no])->update($data);
        /**2*///修改商品表|查询当前订单商品的-->所有商品（商品ID，商品数量，商品规格ID）
        $order = M("order")->field('order_id,pay_code,pay_name,coupon_price,order_amount,user_id')->where(["order_sn"=>$out_trade_no])->find(); //订单表
        $order_goods = M("order_goods")->field("goods_id,goods_num,spec_key,spec_key_name")->where(["order_id"=>$order['order_id']])->find(); //订单商品表
        //根据订单商品的商品ID，查询出商品表的（商品销量、库存数量）
        $goods_num =  M("goods")->field('sales_sum,store_count')->where("goods_id",$order_goods['goods_id'])->find();
        $sales_sum = $goods_num['sales_sum'] + $order_goods['goods_num'];//商品销量
        $kucun =  $goods_num['store_count'] - $order_goods['goods_num'];// 商品库存
        //修改商品表（商品销量，商品库存）
        M('goods')->where("goods_id",$order_goods['goods_id'])->update(["sales_sum"=>$sales_sum,'store_count'=>$kucun]);
        /**修改用户账户余额（余额支付才走此地）*/
        $user = Db::name('users')->field('user_money')->where('user_id',$order['user_id'])->find();
        $userMoney2 = $user['user_money'] - $order['order_amount'];
        Db::name('users')->where('user_id',$order['user_id'])->update(['user_money'=>$userMoney2]);
        /**3*///修改商品规格表|查询出对应规格的库存
        $spec = M("spec_goods_price")->field("store_count")->where(['goods_id'=>$order_goods['goods_id'],'key'=>$order_goods['spec_key']])->find();
        $spec_num = $spec['store_count'] - $order_goods['goods_num'];
        //修改商品规格表（规格库存数量）
        M("spec_goods_price")->where(['goods_id'=>$order_goods['goods_id'],'key'=>$order_goods['spec_key']])->update(['store_count'=>$spec_num]);
        /**4*///优惠券处理（修改优惠券使用状态）
        if ($order['coupon_price'] != 0) {
            M("coupon_exchange")->where(['user_id'=>$order['user_id'], 'status'=>0, 'money'=>$order['coupon_price']])->update(['status'=>1]);
        }
        /**5*///订单表-->到期时间
        if ($order_goods['spec_key_name'] == '年份:一年') {
            $oneYear = strtotime('+1 year',time());
            $map['expire_date'] = $oneYear;
        } if ($order_goods['spec_key_name'] == '年份:三年') {
            $oneYear = strtotime('+3 year',time());
            $map['expire_date'] = $oneYear;
        } if ($order_goods['spec_key_name'] == '年份:五年') {
            $oneYear = strtotime('+5 year',time());
            $map['expire_date'] = $oneYear;
        }
        M("order")->where(["order_sn"=>$out_trade_no])->update($map);
        /**6*///添加支付记录
        $pay['pay_desc'] = '订单支付';
        $pay['is_online'] = 0; //是否在线支付
        $pay['pay_code'] = $order['pay_code'];
        $pay['pay_name'] = $order['pay_name'];
        M("payment")->insert($pay); //添加支付记录
        header('Location: http://vip.bndvip.com/html/orderManagement.html');
    }

}